/*
 * Copyright(c) 2018-? the original author[Wien(luweien@aliyun.com)] or authors.
 *
 */
package org.doll.it.web.exception;

import javax.servlet.http.HttpServletRequest;

import org.doll.it.base.enums.CodeEnum;
import org.doll.it.base.exception.BaseException;
import org.doll.it.base.util.ResultUtils;
import org.doll.it.base.vo.ResultVO;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import lombok.extern.slf4j.Slf4j;

/**
 * 全局错误/异常处理，统一返回JSON
 * 
 * @author Wien(luweien@aliyun.com)
 *
 */
@Slf4j
@ControllerAdvice
public class ExceptionHanlder {

	/**
	 * 通用异常处理
	 */
	@ResponseBody
	@ExceptionHandler(value = Exception.class)
	public ResultVO<String> commExceptionHandler(HttpServletRequest req, Exception e) {
		log.error(e.getMessage(), e);
		return ResultUtils.newError(e.getMessage());
	}

	/**
	 * 自定义异常处理
	 */
	@ResponseBody
	@ExceptionHandler(value = BaseException.class)
	public ResultVO<String> baseExceptionHandler(HttpServletRequest req, BaseException e) {
		Integer code = e.getCode();
		if (code != null) {
			log.error(e.getMessage(), e);
			return ResultUtils.newInstance(e.getCode(), e.getMessage());
		}
		return commExceptionHandler(req, e);
	}

	/**
	 * 参数错误处理
	 */
	@ResponseBody
	@ExceptionHandler(value = IllegalArgumentException.class)
	public ResultVO<String> illegalStateExceptionHandler(HttpServletRequest req, IllegalArgumentException e) {
		log.error(e.getMessage(), e);
		return ResultUtils.newInstance(CodeEnum.PARAMETER_ERROR, e.getMessage());
	}

	/**
	 * 空指针处理
	 */
	@ResponseBody
	@ExceptionHandler(value = NullPointerException.class)
	public ResultVO<String> nullPointerExceptionHandler(HttpServletRequest req, NullPointerException e) {
		log.error(e.getMessage(), e);
		return ResultUtils.newError(CodeEnum.NULL_POINT_EXCEPTION);
	}

	/**
	 * 404处理
	 */
	@ResponseBody
	@ExceptionHandler(value = NoHandlerFoundException.class)
	public ResultVO<String> notFoundHandler(HttpServletRequest req, NoHandlerFoundException e) {
		log.error(e.getMessage(), e);
		return ResultUtils.newError(CodeEnum.NOT_FOUND, e.getMessage());
	}

}
